const { query } = require('../config/db');

/**
 * 检查用户是否为停车场管理员
 * @param {number} userId - 用户ID
 * @returns {Promise<Object|null>} 返回停车场管理员信息或null
 */
async function checkParkingOperatorRole(userId) {
  try {
    if (!userId) {
      return null;
    }

    const roleQuery = `
      SELECT 
        plm.parking_lot_id,
        pl.name as parking_lot_name,
        pl.status as parking_lot_status,
        pl.total_spaces
      FROM parking_lot_managers plm
      JOIN parking_lots pl ON plm.parking_lot_id = pl.id
      WHERE plm.user_id = ? AND pl.status IN ('approved', 'inactive')
    `;

    const result = await query(roleQuery, [userId]);

    if (result.length === 0) {
      return null;
    }

    // 如果用户管理多个停车场，返回第一个（后续可扩展支持多停车场）
    const parkingLot = result[0];

    return {
      role_type: 'parking_operator',
      parking_lot_id: parkingLot.parking_lot_id,
      parking_lot_name: parkingLot.parking_lot_name,
      parking_lot_status: parkingLot.parking_lot_status,
      total_spaces: parkingLot.total_spaces,
      permissions: [
        'view_parking_orders',
        'manage_parking_orders',
        'view_parking_statistics',
        'update_order_times',
        'manage_parking_spaces'
      ]
    };

  } catch (error) {
    console.error('检查停车场管理员角色错误:', error);
    return null;
  }
}

/**
 * 验证用户对特定停车场的管理权限
 * @param {number} userId - 用户ID
 * @param {number} parkingLotId - 停车场ID
 * @returns {Promise<boolean>} 是否有权限
 */
async function validateParkingLotAccess(userId, parkingLotId) {
  try {
    if (!userId || !parkingLotId) {
      return false;
    }

    const accessQuery = `
      SELECT COUNT(*) as has_permission
      FROM parking_lot_managers plm
      JOIN parking_lots pl ON plm.parking_lot_id = pl.id
      WHERE plm.user_id = ? AND plm.parking_lot_id = ? AND pl.status IN ('approved', 'inactive')
    `;

    const result = await query(accessQuery, [userId, parkingLotId]);
    return result[0].has_permission > 0;

  } catch (error) {
    console.error('验证停车场访问权限错误:', error);
    return false;
  }
}

/**
 * 获取用户管理的停车场列表
 * @param {number} userId - 用户ID
 * @returns {Promise<Array>} 停车场列表
 */
async function getUserManagedParkingLots(userId) {
  try {
    if (!userId) {
      return [];
    }

    const parkingLotsQuery = `
      SELECT 
        pl.id,
        pl.name,
        pl.address,
        pl.total_spaces,
        pl.status,
        pl.created_at
      FROM parking_lot_managers plm
      JOIN parking_lots pl ON plm.parking_lot_id = pl.id
      WHERE plm.user_id = ? AND pl.status IN ('approved', 'inactive')
      ORDER BY pl.name ASC
    `;

    const result = await query(parkingLotsQuery, [userId]);
    return result;

  } catch (error) {
    console.error('获取用户管理的停车场列表错误:', error);
    return [];
  }
}

/**
 * 检查用户是否有特定权限
 * @param {number} userId - 用户ID
 * @param {string} permission - 权限名称
 * @param {number} parkingLotId - 停车场ID（可选）
 * @returns {Promise<boolean>} 是否有权限
 */
async function checkUserPermission(userId, permission, parkingLotId = null) {
  try {
    // 首先检查用户是否为停车场管理员
    const operatorRole = await checkParkingOperatorRole(userId);

    if (!operatorRole) {
      return false;
    }

    // 如果指定了停车场ID，验证用户是否有该停车场的权限
    if (parkingLotId) {
      const hasAccess = await validateParkingLotAccess(userId, parkingLotId);
      if (!hasAccess) {
        return false;
      }
    }

    // 检查权限是否在允许的权限列表中
    return operatorRole.permissions.includes(permission);

  } catch (error) {
    console.error('检查用户权限错误:', error);
    return false;
  }
}

/**
 * 获取用户角色信息（包括普通用户和停车场管理员）
 * @param {number} userId - 用户ID
 * @returns {Promise<Object>} 用户角色信息
 */
async function getUserRoleInfo(userId) {
  try {
    if (!userId) {
      return {
        role_type: 'user',
        permissions: ['view_own_orders', 'create_booking', 'manage_vehicles']
      };
    }

    // 检查是否为停车场管理员
    const operatorRole = await checkParkingOperatorRole(userId);

    if (operatorRole) {
      return operatorRole;
    }

    // 默认为普通用户
    return {
      role_type: 'user',
      permissions: ['view_own_orders', 'create_booking', 'manage_vehicles']
    };

  } catch (error) {
    console.error('获取用户角色信息错误:', error);
    return {
      role_type: 'user',
      permissions: ['view_own_orders', 'create_booking', 'manage_vehicles']
    };
  }
}

/**
 * 验证订单是否属于用户管理的停车场
 * @param {number} userId - 用户ID
 * @param {number} orderId - 订单ID
 * @returns {Promise<boolean>} 是否有权限访问该订单
 */
async function validateOrderAccess(userId, orderId) {
  try {
    if (!userId || !orderId) {
      return false;
    }

    const orderAccessQuery = `
      SELECT COUNT(*) as has_access
      FROM orders o
      JOIN parking_lot_managers plm ON o.parking_lot_id = plm.parking_lot_id
      WHERE plm.user_id = ? AND o.id = ?
    `;

    const result = await query(orderAccessQuery, [userId, orderId]);
    return result[0].has_access > 0;

  } catch (error) {
    console.error('验证订单访问权限错误:', error);
    return false;
  }
}

module.exports = {
  checkParkingOperatorRole,
  validateParkingLotAccess,
  getUserManagedParkingLots,
  checkUserPermission,
  getUserRoleInfo,
  validateOrderAccess
};